package com.xyw.code.platform.webapps.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyw.code.platform.common.entity.dto.RoleDTO;
import com.xyw.code.platform.common.entity.enums.CommonStatusEnum;
import com.xyw.code.platform.common.entity.enums.RoleConstant;
import com.xyw.code.platform.common.entity.po.*;
import com.xyw.code.platform.common.entity.util.XUtil;
import com.xyw.code.platform.webapps.dao.SysRoleMapper;
import com.xyw.code.platform.webapps.service.ISysDeptService;
import com.xyw.code.platform.webapps.service.ISysRoleDeptService;
import com.xyw.code.platform.webapps.service.ISysRoleMenuService;
import com.xyw.code.platform.webapps.service.ISysRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author xyw
 * @since 2020-02-07
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Resource
    private ISysRoleDeptService roleDeptService;

    @Resource
    private ISysRoleMenuService roleMenuService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private SysRoleMapper sysRoleMapper;


    @Override
    public List<SysRole> selectRoleList(String roleName, String deptId) {
        if (StringUtils.isNotEmpty(deptId) && !"0".equals(deptId)){
            deptId = null;
        }
        List<SysRole> sysRoles =  sysRoleMapper.query(SysRole.builder().deptId(deptId).roleName(roleName).build());
        return sysRoles.stream().peek(sysRole ->
                sysRole.setRoleDepts(roleDeptService.getRoleDeptIds(sysRole.getId()).stream().map(SysRoleDept::getDeptId).collect(Collectors.toList()))
        ).collect(Collectors.toList());
    }

    @Override
    public List<SysRole> selectRoleListByUserId(String userId) {
        return baseMapper.listRolesByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveRoleMenu(RoleDTO roleDTO) {
        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleDTO,role);
        StringJoiner deptIds = new StringJoiner(",");
        //如果是自定义的话 再去取部门集合
        if(RoleConstant.RoleDsTypeEnum.CUSTOMIZE.getType()==roleDTO.getDsType() &&  roleDTO.getRoleDepts().size()>0){
            roleDTO.getRoleDepts().forEach(id->{
                deptIds.add(id);
            });
            role.setDsScope(deptIds.toString());
        }
        save(role);
        roleDTO.setId(role.getId());
        //维护角色菜单
        saveRoleMenuItem(roleDTO);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateRoleMenu(RoleDTO roleDTO) {
        //删除菜单
        roleMenuService.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId,roleDTO.getId()));
        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleDTO,role);
        StringJoiner deptIds = new StringJoiner(",");
        //如果是自定义的话 再去取部门集合
        if(RoleConstant.RoleDsTypeEnum.CUSTOMIZE.getType()==roleDTO.getDsType() &&  roleDTO.getRoleDepts().size()>0){
            roleDTO.getRoleDepts().forEach(id->{
                deptIds.add(id);
            });
            role.setDsScope(deptIds.toString());
        }
        updateById(role);
        saveRoleMenuItem(roleDTO);
        return true;
    }

    @Override
    public List<Map<String, Object>> getDsTypes(String deptId) {
        List<Map<String, Object>> dsTypes = new ArrayList<>();

        SysDept dept = deptService.getById(deptId);
        //如果上级是空
        if(dept!=null && XUtil.parentIsNull(dept.getParentId())){
            Map<String,Object> oneMap = new HashMap();
            oneMap.put("id",1);
            oneMap.put("desc","全部");
            dsTypes.add(oneMap);
        }

        Map<String,Object> twoMap = new HashMap();
        twoMap.put("id",2);
        twoMap.put("desc","本级");
        dsTypes.add(twoMap);
        Map<String,Object> threeMap = new HashMap();
        threeMap.put("id",3);
        threeMap.put("desc","本级及以下");
        dsTypes.add(threeMap);
        Map<String,Object> fourMap = new HashMap();
        fourMap.put("id",4);
        fourMap.put("desc","自定义");
        dsTypes.add(fourMap);
        return dsTypes;
    }

    @Override
    public List<SysMenu> findMenuListByRoleId(String roleId) {
        return baseMapper.findMenuListByRoleId(roleId);
    }

    /**
     * 维护角色菜单
     * @param roleDTO
     */
    private void saveRoleMenuItem(RoleDTO roleDTO){
        //维护角色菜单
        List<SysRoleMenu> roleMenus = roleDTO.getRoleMenus();
        if (CollectionUtil.isNotEmpty(roleMenus)) {
            List<SysRoleMenu> rms = roleMenus.stream().map(sysRoleMenu -> {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(roleDTO.getId());
                roleMenu.setMenuId(sysRoleMenu.getMenuId());
                return roleMenu;
            }).collect(Collectors.toList());
            roleMenuService.saveBatch(rms);
        }
    }
}
